﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.Components;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.PrintExport;
using Aliyeye.Car.Net.UI.PopupDialog;

namespace Aliyeye.Car.Net.UI.OrderModel
{
    /// <summary>
    /// 违章保留退款
    /// </summary>
    public partial class ReturnIllegalList : Aliyeye.Car.Net.UI.BaseForm
    {
        private string strSearch = string.Empty;

        public ReturnIllegalList()
        {
            InitializeComponent();
        }

        private void ReturnIllegalList_Load(object sender, EventArgs e)
        {
            this.pager1.PageCurrent = 1;
            this.pager1.Bind();
        }

        private int dgvBind()
        {
            string _strSql = "OrderSataus='true' and Type!='4'and IsReturnIllegal !='true' ";
            string strWhere = strSearch;
            PageData pageData = new PageData(this, pager1, overlay);
            pageData.TableName = "Reserve left join Car on Car.Id=Reserve.CarId left join Customer on Customer.Id=Reserve.CustId left join Accounts_Users UserInfo on UserInfo.UserId=Reserve.ReturnIllegalUserID ";
            pageData.PrimaryKey = "Reserve.Id";
            pageData.OrderStr = "Reserve.InpuTime desc";
            pageData.PageIndex = this.pager1.PageCurrent;
            pageData.PageSize = this.pager1.PageSize;
            pageData.QueryCondition = _strSql + strWhere.ToString();
            pageData.QueryFieldName = "Reserve.Id as ReserveID,Customer.Code,SettlementDate,ComName,Name,ReceivedAmount,  IllegalRetention,((select sum(Price)  from Illegal where Illegal.CarCode=Car.Code and Reserve.BookTime<=Illegal.Time and Illegal.Time<=Reserve.EndBooktime)-case when TotalFines is null then 0 else TotalFines end) as IllegalSumAmount,IsReturnIllegal,ReturnIllegalDate,UserInfo.TrueName as ReturnIllegalUserName,ReturnIllegalAmount,TotalAmount,Car.Code as CarCode, Booktime, EndBooktime, (select Count(*)  from Illegal where Illegal.Status='未结算' and Illegal.CarCode=Car.Code and Reserve.BookTime<=Illegal.Time and Illegal.Time<=Reserve.EndBooktime) as IllegalCount ";

            DataSet ds = pageData.QueryDataTable();
            dgvInfo.AutoGenerateColumns = false;
            dgvInfo.DataSource = this.pager1.bindingSource;
            return pageData.TotalCount;
        }

        private int pager1_EventPaging(EventPagingArg e)
        {
            return dgvBind();
        }

        private void dgvInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (IsANonHeaderButtonCell(e))
            {
                ButtonClicked(e);
            }
            if (IsANonHeaderLinkButtonCell(e))
            {
                LinkButtonClicked(e);
            }
        }

        private void ButtonClicked(DataGridViewCellEventArgs e)
        {
            String strButtonContent = dgvInfo.Columns[e.ColumnIndex].Name;
            String id = dgvInfo.Rows[e.RowIndex].Cells["ReserveID"].Value.ToString();
            if (strButtonContent.Trim().Equals("退押金"))
            {
                ReturnIllegalInfo userForm = new ReturnIllegalInfo(Convert.ToInt32(id));
                userForm.ShowDialog();
            }
            this.pager1.Bind();
        }

        private void LinkButtonClicked(DataGridViewCellEventArgs e)
        {
            String strButtonContent = dgvInfo.Columns[e.ColumnIndex].Name;
            int id = Convert.ToInt32(dgvInfo.Rows[e.RowIndex].Cells["ReserveID"].Value.ToString());
            String count = dgvInfo.Rows[e.RowIndex].Cells["罚单"].Value.ToString();
            if (count.Trim() == "0")
                return;
            if (strButtonContent.Trim().Equals("罚单"))
            {
                IllegalList userForm = new IllegalList(id);
                userForm.ShowDialog();
            }
            //this.pager1.Bind();
        }

        private bool IsANonHeaderButtonCell(DataGridViewCellEventArgs cellEvent)
        {
            if (dgvInfo.Columns[cellEvent.ColumnIndex] is
                 DataGridViewButtonColumn &&
                 cellEvent.RowIndex != -1)
            { return true; }
            else { return (false); }
        }

        private bool IsANonHeaderLinkButtonCell(DataGridViewCellEventArgs cellEvent)
        {
            if (dgvInfo.Columns[cellEvent.ColumnIndex] is
                 DataGridViewLinkColumn &&
                 cellEvent.RowIndex != -1)
            { return true; }
            else { return (false); }
        }

        //搜索
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string strWhere2 = "";
            if (!string.IsNullOrEmpty(txtCustomName.Text))
            {
                strWhere2 += " and Customer.Name like '%" + txtCustomName.Text + "%'";
            }
            strSearch = strWhere2;
            this.pager1.Bind();
        }

        //全部
        private void btnAll_Click(object sender, EventArgs e)
        {
            strSearch = "";
            txtCustomName.Text = "";

            this.pager1.Bind();
        }

        private void dgvInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvInfo.Rows.Count; )
                {
                    this.dgvInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;
            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "实退金额")
            {
                decimal IllegalSumAmount = 0;
                if (!string.IsNullOrEmpty(this.dgvInfo.Rows[e.RowIndex].Cells["罚单金额"].Value.ToString()))
                {
                    IllegalSumAmount = Convert.ToDecimal(this.dgvInfo.Rows[e.RowIndex].Cells["罚单金额"].Value);
                    this.dgvInfo.Rows[e.RowIndex].Cells["罚单金额"].Value = IllegalSumAmount;
                }
                else
                {
                    this.dgvInfo.Rows[e.RowIndex].Cells["罚单金额"].Value = "0";
                }

                if (e.Value == null || e.Value.ToString().Trim() == "")
                {
                    decimal IllegalRetention = Convert.ToDecimal(this.dgvInfo.Rows[e.RowIndex].Cells["应退金额"].Value);
                    decimal returnAdmount = IllegalRetention - IllegalSumAmount;

                    e.Value = returnAdmount;
                }
            }

            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "结帐日期" || this.dgvInfo.Columns[e.ColumnIndex].Name == "退款日期" || this.dgvInfo.Columns[e.ColumnIndex].Name == "起租日期" || this.dgvInfo.Columns[e.ColumnIndex].Name == "还车日期")
            {
                if (e.Value != null && !string.IsNullOrEmpty(e.Value.ToString()))
                {
                    e.Value = Convert.ToDateTime(e.Value).ToString("yyyy-MM-dd HH:mm:ss");
                }
            }

            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "状态")
            {
                if (e.Value != null && !string.IsNullOrEmpty(e.Value.ToString()))
                {
                    if (Convert.ToBoolean(e.Value))
                    {
                        e.Value = "已退款";
                        e.CellStyle.ForeColor = Color.Blue;
                    }
                    else
                    {
                        e.Value = "未退款";
                        e.CellStyle.ForeColor = Color.Red;
                    }
                }
                else
                {
                    e.Value = "未退款";
                    e.CellStyle.ForeColor = Color.Red;
                }
            }
        }

        # region 选择客户

        private void dgvCustomerInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;

            if (this.dgvCustomerInfo.Columns[e.ColumnIndex].Name == "客户类型")
            {
                if (e.Value != null)
                {
                    if (e.Value.ToString().Trim() == "1")
                    {
                        e.Value = "个体户客户";
                    }
                    else
                    {
                        e.Value = "企业客户";
                    }
                }
            }
        }

        private void dgvCustomerInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvCustomerInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvCustomerInfo.Rows.Count; )
                {
                    this.dgvCustomerInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        string customerName = "";

        private void dgvCustomerInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                this.txtCustomName.Text = this.dgvCustomerInfo.CurrentRow.Cells["姓名"].Value.ToString();
                customerName = this.txtCustomName.Text;
                this.dgvCustomerInfo.Visible = false;
            }
        }

        private void txtCustomName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string strSearch = txtCustomName.Text;
                if (string.IsNullOrEmpty(strSearch))
                {
                    DialogWarning dia = new DialogWarning("客户名不能为空！");
                    dia.ShowDialog();
                    return;
                }
                else
                {
                    DisplayCustomeLIst(strSearch, "姓名");
                }
            }
        }

        private void DisplayCustomeLIst(string strSearch, string type)
        {
            if (string.IsNullOrEmpty(strSearch))
            {
                return;
            }

            overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;
            string strSelectWhere = "";
            if (type == "姓名")
            {
                strSelectWhere = " Name like '%" + strSearch + "%'";
            }
            if (type == "客户编号")
            {
                strSelectWhere = " Code like '%" + strSearch + "%'";
            }
            DataSet ds = null;
            dgvCustomerInfo.DataSource = null;
            dgvCustomerInfo.AutoGenerateColumns = false;

            CustomerSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.CustomerSvc.SoapHeaderClass();
            ServiceManipulator.SafeAsyncExecution<CustomerSvc.CustomerServiceSoapClient>(
                proxy => proxy.GetList(sopaHeader, strSelectWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        ds = (DataSet)result.Result;
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            dgvCustomerInfo.DataSource = ds.Tables[0];
                            this.dgvCustomerInfo.Visible = true;
                            this.dgvCustomerInfo.Focus();
                        }
                        else
                        {
                            //txtcustcode.Text = customerCode;
                            txtCustomName.Text = customerName;
                            PageCommon.Alert("查找的客户不存在，请重新查找！");
                        }
                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message);
                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

        }
        #endregion

    }
}
